import Taro from '@tarojs/taro'

/**
 * 格式化时间
 * @param {Date|string|number} date 时间
 * @param {string} format 格式
 */
export function formatTime(date, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) return ''
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  const second = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second)
}

/**
 * 格式化价格
 * @param {number} price 价格
 * @param {number} decimals 小数位数
 */
export function formatPrice(price, decimals = 2) {
  if (price === null || price === undefined) return '0.00'
  return Number(price).toFixed(decimals)
}

/**
 * 防抖函数
 * @param {Function} func 要防抖的函数
 * @param {number} wait 等待时间
 */
export function debounce(func, wait = 300) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

/**
 * 节流函数
 * @param {Function} func 要节流的函数
 * @param {number} limit 时间间隔
 */
export function throttle(func, limit = 300) {
  let inThrottle
  return function executedFunction(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

/**
 * 获取图片完整URL
 * @param {string} url 图片路径
 */
export function getImageUrl(url) {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `${process.env.NODE_ENV === 'development' ? 'http://localhost:8080' : 'https://api.youkeleling.com'}${url}`
}

/**
 * 手机号脱敏
 * @param {string} phone 手机号
 */
export function maskPhone(phone) {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

/**
 * 验证手机号
 * @param {string} phone 手机号
 */
export function validatePhone(phone) {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}

/**
 * 复制到剪贴板
 * @param {string} text 要复制的文本
 */
export function copyToClipboard(text) {
  return new Promise((resolve, reject) => {
    Taro.setClipboardData({
      data: text,
      success: () => {
        Taro.showToast({
          title: '复制成功',
          icon: 'success'
        })
        resolve()
      },
      fail: reject
    })
  })
}

/**
 * 获取当前页面路径
 */
export function getCurrentPagePath() {
  const pages = Taro.getCurrentPages()
  const currentPage = pages[pages.length - 1]
  return currentPage ? currentPage.route : ''
}

/**
 * 页面跳转
 * @param {string} url 页面路径
 * @param {object} params 参数
 */
export function navigateTo(url, params = {}) {
  let fullUrl = url
  const queryString = Object.keys(params)
    .map(key => `${key}=${encodeURIComponent(params[key])}`)
    .join('&')
  
  if (queryString) {
    fullUrl += (url.includes('?') ? '&' : '?') + queryString
  }
  
  return Taro.navigateTo({ url: fullUrl })
}

/**
 * 显示加载提示
 * @param {string} title 提示文字
 */
export function showLoading(title = '加载中...') {
  Taro.showLoading({ title, mask: true })
}

/**
 * 隐藏加载提示
 */
export function hideLoading() {
  Taro.hideLoading()
}

/**
 * 显示成功提示
 * @param {string} title 提示文字
 */
export function showSuccess(title) {
  Taro.showToast({
    title,
    icon: 'success',
    duration: 2000
  })
}

/**
 * 显示错误提示
 * @param {string} title 提示文字
 */
export function showError(title) {
  Taro.showToast({
    title,
    icon: 'none',
    duration: 2000
  })
}